﻿@page "/SystemPage"

<h3>系统信息</h3>

<UploadProgress Progress="_progress" Overlay="_overlay"></UploadProgress>

<MCard Class="mt-4">
    <MCard Class="pa-4">
        <MToolbar Rounded="true"
        Color="teal"
        Dark>
            <MToolbarTitle>系统信息</MToolbarTitle>
            <MSpacer></MSpacer>
            <MButton IconName="@(showSystemInfo?"mdi-chevron-double-down":"mdi-chevron-double-right")" OnClick="GetSystemInfo"></MButton>
        </MToolbar>
        <MDivider />
        <ExpandTransition>
            <MCard Show="showSystemInfo" Color="grey lighten-3" class="mx-auto">
                @foreach (var item in systemInfoList)
                {
                    <h4>@item</h4>
                }
            </MCard>
        </ExpandTransition>
    </MCard>
</MCard>

<MCard Class="mt-4">
    <MCard Class="pa-4">
        <MToolbar Rounded="true"
        Color="teal"
        Dark>
            <MToolbarTitle>基础设施</MToolbarTitle>
            <MSpacer></MSpacer>
            <MButton IconName="@(showAppInfo?"mdi-chevron-double-down":"mdi-chevron-double-right")" OnClick="GetAllAppInfo"></MButton>
        </MToolbar>
        <MDivider />
        <ExpandTransition>
            <MCard Show="showAppInfo" Color="grey lighten-3" class="mx-auto">
                <MDataTable Items="appDataList"
                Headers="headers"
                HideDefaultFooter
                Class="elevation-1">

                    <ItemContent Context="item">
                        <tr>
                            <td>@item.Item.ChName</td>
                            <td>
                                <MIcon Color="@(item.Item.IsExist ? "green" : "red")">
                                    @(item.Item.IsExist ? "mdi-check-circle-outline" : "mdi-close-circle-outline")
                                </MIcon>
                            </td>
                            <td>@item.Item.OutData</td>
                            <td>
                                @if (!item.Item.IsExist)
                                {
                                    <MButton Color="primary" OnClick="()=>Instaill(item.Item)">
                                        安装
                                    </MButton>
                                    <MButton Color="primary" OnClick="()=>RefreshAppStatus(item.Item)">
                                        重新检测
                                    </MButton>
                                }
                            </td>
                        </tr>
                    </ItemContent>
                </MDataTable>

            </MCard>
        </ExpandTransition>
    </MCard>
</MCard>

@code {
    [Inject]
    public ISshClientService SshClientService { get; set; }
    [Inject]
    public ILocalFileService LocalFileService { get; set; }

    public double _progress { get; set; }
    private bool _overlay = false;
    /// <summary>
    /// 显示系统信息
    /// </summary>
    private bool showSystemInfo = false;
    /// <summary>
    /// 显示应用信息
    /// </summary>
    private bool showAppInfo = false;
    private List<string> systemInfoList = new List<string>();
    private List<string> appInfoList = new List<string>();

    private List<DataTableHeader<SystemAppDataViewMode>> headers = new List<DataTableHeader<SystemAppDataViewMode>>
    {
        new DataTableHeader<SystemAppDataViewMode> { Text = "应用名称", Value = nameof(SystemAppDataViewMode.ChName) },
        new DataTableHeader<SystemAppDataViewMode> { Text = "安装状态", Value = nameof(SystemAppDataViewMode.IsExist) },
        new DataTableHeader<SystemAppDataViewMode> { Text = "安装信息", Value = nameof(SystemAppDataViewMode.OutData) },
        new DataTableHeader<SystemAppDataViewMode> { Text = "操作", Value = "actions", Sortable = false }
    };

    private List<SystemAppDataViewMode> appDataList = SystemAppDataViewMode.AppData;

    private void GetSystemInfo()
    {
        LinuxCommandResultBase linuxCommandResultBase = SshClientService.ExecuteCommand(() => new SystemInfoCommand());
        if (!linuxCommandResultBase.Error.IsNullOrWhiteSpace())
            throw new Exception(linuxCommandResultBase.Error);
        systemInfoList = linuxCommandResultBase.Output.Split('\n').ToList();
        showSystemInfo = !showSystemInfo;
    }

    private void GetAllAppInfo()
    {
        appInfoList.Clear();
        foreach (var item in appDataList)
        {
            item.IsExist = false;
            LinuxCommandResultBase linuxCommandResultBase = SshClientService.ExecuteCommand(() => new SearchAppCommand()
                {
                    AppName = item.AppName
                });
            // if (!linuxCommandResultBase.Error.IsNullOrWhiteSpace())
            //     throw new Exception(linuxCommandResultBase.Error);
            if (linuxCommandResultBase.Output.IsNullOrWhiteSpace())
            {
                item.IsExist = false;
            }
            else if (linuxCommandResultBase.Output.IndexOf("version")>=0)
            {
                item.OutData = linuxCommandResultBase.Output;
                item.IsExist = true;
            }
            linuxCommandResultBase.Output.Split('\n').ToList().ForEach(e =>
            {
                appInfoList.Add(e);
            });
        }
        showAppInfo = !showAppInfo;
    }

    private void RefreshAppStatus(SystemAppDataViewMode viewMode)
    {
        viewMode.IsExist = false;
        LinuxCommandResultBase linuxCommandResultBase = SshClientService.ExecuteCommand(() => new SearchAppCommand()
            {
                AppName = viewMode.AppName
            });
        if (linuxCommandResultBase.Output.IsNullOrWhiteSpace())
        {
            viewMode.IsExist = false;
        }
        else if (linuxCommandResultBase.Output.IndexOf("version") >= 0)
        {
            viewMode.OutData = linuxCommandResultBase.Output;
            viewMode.IsExist = true;
        }
    }
    /// <summary>
    /// 安装应用
    /// </summary>
    private async Task Instaill(SystemAppDataViewMode viewMode)
    {
        //安装Java
        if (viewMode.AppName=="java"){
            await Install_Java(viewMode);
        }
        if (viewMode.AppName == "nginx")
        {
            await Install_Nginx(viewMode);
        }

    }
    /// <summary>
    /// 安装Java
    /// </summary>
    private async Task Install_Java(SystemAppDataViewMode viewMode)
    {
        //上传压缩文件
        var javaFileKv = await LocalFileService.OpenFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppFile", viewMode.AppName, "jdk-8u441-linux-x64.tar.gz"));
        await SshClientService.UploadFileAsync(javaFileKv.Value, "/opt/jdk-8u441-linux-x64.tar.gz", (double d) =>
        {
            _overlay = true;
            _progress = d;
            StateHasChanged();
        });
        _overlay = false;
        StateHasChanged();
        //解压压缩文件
        TarCommand tarCommand = new TarCommand() { CommandType = TarCommandTypeEnum.UnPackage, Source = "/opt/jdk-8u441-linux-x64.tar.gz", OutputFile = "/opt" };
        LinuxCommandResultBase linuxCommandResultBase = SshClientService.ExecuteCommand(tarCommand);
        //配置环境变量
        AddEnvCommand javaEnv = new AddEnvCommand() { EnvName = "JAVA_HOME", EnvValue = "/opt/jdk1.8.0_441" ,FileName="java_home"};
        AddEnvCommand javaPathEnv = new AddEnvCommand() { EnvName = "PATH", EnvValue = "/opt/jdk1.8.0_441/bin", FileName = "java_home" };
        SourceEnvCommand sourceEnvCommand = new SourceEnvCommand() { FileName = "java_home" };

        SshClientService.ExecuteCommand(javaEnv);
        SshClientService.ExecuteCommand(javaPathEnv);
        SshClientService.ExecuteCommand(sourceEnvCommand);
    }

    /// <summary>
    /// 安装Nginx
    /// </summary>
    private async Task Install_Nginx(SystemAppDataViewMode viewMode)
    {
        string zipFileName = $"nginx-offline-{SshClientService.SshClientConnectInfo.SystemVersionType.ToString().ToLower()}.tar.gz";
        //上传压缩文件
        var zipFileKv = await LocalFileService.OpenFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppFile", viewMode.AppName, zipFileName));
        await SshClientService.UploadFileAsync(zipFileKv.Value, $"/opt/{zipFileName}", (double d) =>
        {
            _overlay = true;
            _progress = d;
            StateHasChanged();
        });
        _overlay = false;
        StateHasChanged();
        //解压压缩文件
        TarCommand tarCommand = new TarCommand() { CommandType = TarCommandTypeEnum.UnPackage, Source = $"/opt/{zipFileName}", OutputFile = "/opt" };
        LinuxCommandResultBase linuxCommandResultBase = SshClientService.ExecuteCommand(tarCommand);
        CdCommand cdCommand = new CdCommand() { Path = $"/opt/nginx-offline" };
        linuxCommandResultBase=SshClientService.ExecuteCommand(cdCommand);
        //安装Nginx
        PackageInstallCommand nginxInstallCommand = new PackageInstallCommand() { PackagePath = "/opt/nginx-offline" };
        linuxCommandResultBase = SshClientService.ExecuteCommand(nginxInstallCommand);
        //启动Nginx
        NginxCommand nginxCommand = new NginxCommand() { CommandType = NginxCommandTypeEnum.Start };
        linuxCommandResultBase = SshClientService.ExecuteCommand(nginxCommand);
        //设置开机启动
        NginxCommand nginxCommand2 = new NginxCommand() { CommandType = NginxCommandTypeEnum.Enable };
        linuxCommandResultBase = SshClientService.ExecuteCommand(nginxCommand2);
    }

    /// <summary>
    /// 安装KeepAlived
    /// </summary>
    /// <param name="viewMode"></param>
    /// <returns></returns>
    private async Task Install_KeepAlived(SystemAppDataViewMode viewMode)
    {
        string zipFileName = $"keepalived-offline-{SshClientService.SshClientConnectInfo.SystemVersionType.ToString().ToLower()}.tar.gz";
        //上传压缩文件
        var zipFileKv = await LocalFileService.OpenFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppFile", viewMode.AppName, zipFileName));
        await SshClientService.UploadFileAsync(zipFileKv.Value, $"/opt/{zipFileName}", (double d) =>
        {
            _overlay = true;
            _progress = d;
            StateHasChanged();
        });
        _overlay = false;
        StateHasChanged();
        //解压压缩文件
        TarCommand tarCommand = new TarCommand() { CommandType = TarCommandTypeEnum.UnPackage, Source = $"/opt/{zipFileName}", OutputFile = "/opt" };
        LinuxCommandResultBase linuxCommandResultBase = SshClientService.ExecuteCommand(tarCommand);
        CdCommand cdCommand = new CdCommand() { Path = $"/opt/keepalived-offline" };
        linuxCommandResultBase = SshClientService.ExecuteCommand(cdCommand);
        //安装KeepAlived
        PackageInstallCommand nginxInstallCommand = new PackageInstallCommand() { PackagePath = "/opt/keepalived-offline" };
        linuxCommandResultBase = SshClientService.ExecuteCommand(nginxInstallCommand);
    }
}
